<template>
  <div>
  <div>
    <el-row>
      <el-col span="5">
        <el-radio-group v-model="selectsearch" @change="clearInput">
          <el-radio :label="3" >按部门Id查询</el-radio>
          <el-radio :label="6">按员工Id查询</el-radio>
        </el-radio-group>
      </el-col>
      <el-col span="4">
        <el-input
          v-model="searchInput"
          placeholder="输入ID"
          prefix-icon="el-icon-search"
          @input="watchsearch"
        >

        </el-input>

      </el-col>
      <el-col :span="8">

        <el-select v-model="showvalue" placeholder="排序类型(默认DepId升序)" @change="showDepartmentOrderBy(showvalue)">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="2">

        <el-button @click="exportExcel">导出部门信息表</el-button>

      </el-col>
      <el-col :span="4">
        <el-button @click="returnlogin">返回首页</el-button>
      </el-col>
    </el-row>


  </div>
  <div id="tables">
    <el-table
      :data="department_emp"
      :row-style="{height: '0'}"
      :cell-style="{padding: '0'}"
      style="width: 100%"
      @row-click="getDetails"
      id="out-table"
    >
      <!--        <el-table-column label width="35">-->
      <!--          <template slot-scope="scope">-->
      <!--            <el-radio :label="scope.row.name" v-model="radioId">&nbsp;</el-radio>-->
      <!--          </template>-->
      <!--        </el-table-column>-->
      <el-table-column align="center" prop="departmentId" label="部门Id" width="75"></el-table-column>
      <el-table-column align="center" prop="departmentName" label="部门名" width="100"></el-table-column>
      <el-table-column align="center" prop="userId" label="员工Id" width="100" fixed></el-table-column>
      <el-table-column align="center" prop="username" label="姓名" width="75"></el-table-column>
      <el-table-column align="center" prop="role" label="权限级别" width="100"></el-table-column>
        <el-table-column align="center" prop="workId" label="岗位Id" width="100"></el-table-column>
      <el-table-column align="center" prop="workName" label="职位" width="75"></el-table-column>
      <el-table-column align="center" prop="istrain" label="是否培训" width="50"></el-table-column>
      <el-table-column align="center" prop="iswork" label="是否在岗" width="50"></el-table-column>
      <el-table-column fixed="right" width="400" label="操作">
        <template slot-scope="scope">
          <el-button v-show="scope.row.role == 'user'&&scope.row.iswork==`0`" @click="addNewDeper(scope.row)"style="padding: 3px" size="mini" type="success">添加部门成员</el-button>
          <el-button v-show="scope.row.role =='user'&&scope.row.iswork==`1`" @click="openshowDeper(scope.row)"style="padding: 3px" size="mini" type="primary">查看所属部长</el-button>
          <el-button v-show="scope.row.role =='department'" @click="changeNewDeper(scope.row)"style="padding: 3px" size="mini" type="warning">更换部门部长</el-button>
          <el-button @click="openEditdialog(scope.row)" style="padding: 3px" size="mini" v-show="scope.row.iswork==`1`">修改成员资料</el-button>
          <!--            <el-button style="padding: 3px" size="mini" type="primary">查看高级资料</el-button>-->
          <el-button @click="outEmp(scope.row)" v-show="scope.row.role =='user'&&scope.row.iswork==`1`" style="padding: 3px" size="mini" type="danger">移出部门</el-button>
          <el-button @click="deleteEmp(scope.row)" v-show="scope.row.role =='department'" style="padding: 3px" size="mini" type="danger">解散部门</el-button>

        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="编 辑 信 息"
      :visible.sync="EditdialogVisable"
      width="80%"
      :before-close="handleClose">
      <el-form ref="form" label-width="100px" v-model="department_emps" :rules="rule">
        <el-row>
          <el-col :span="6">
            <el-form-item label="部门id">
              <el-input v-model="department_emps.departmentId" disabled="true" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门名称" v-show="department_emps.role=='department'">
              <el-input v-model="department_emps.departmentName" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="员工Id" prop="name">
              <el-input v-model="department_emps.userId" disabled="true" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="员工姓名" prop="name">
              <el-input v-model="department_emps.username"  ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="工号" >
              <el-input v-model="department_emps.workId" disabled="true" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门职位">
              <el-input v-model="department_emps.workName" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelEdit">取 消</el-button>
    <el-button type="primary" @click="submitchangeDep">确 定 修 改</el-button>
  </span>
    </el-dialog>

    <el-dialog
      title="新 增 部 门 人 员"
      :visible.sync="AddDepdialogVisable"
      width="80%"
      :before-close="handleClose">
      <el-form ref="form" label-width="100px" v-model="department_emps" :rules="rule">
        <el-row>
          <el-col :span="6">
              <el-form-item label="请选择部门">
                <el-select v-model="departmentvalue" placeholder="请选择部门Id" @change="showDepIdAndDepName(departmentvalue)">
                  <el-option
                    v-for="item in dep"
                    :key="item"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>

          </el-col>
          <el-col :span="6">
            <el-form-item label="部门名称" >
              <el-input v-model="department_emps.departmentName"  disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="员工Id" prop="name">
              <el-input v-model="department_emps.userId" disabled="true" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="员工姓名" prop="name">
              <el-input v-model="department_emps.username"  disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="工号" >
              <el-input v-model="department_emps.workId"  ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门职位">
              <el-input v-model="department_emps.workName" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelAdd">取 消</el-button>
    <el-button type="primary" @click="submitAddDep">确 定 添 加</el-button>
  </span>
    </el-dialog>

    <el-dialog
      title="更 换 部 门 部 长"
      :visible.sync="ChangeDepdiaglogVisable"
      width="80%"
      :before-close="handleClose">
      <el-form ref="form" label-width="100px" v-model="department_emps" :rules="rule">
        <el-row>
          <el-col :span="6">
            <el-form-item label="请选择员工ID">
              <el-select v-model="Empvalue" placeholder="请选择员工Id" @change="showuserIdNoWork(Empvalue)">
                <el-option
                  v-for="item in users"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="6">
            <el-form-item label="部门Id" >
              <el-input v-model="department_emps.departmentId"  disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门名称" >
              <el-input v-model="department_emps.departmentName"  disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="员工Id" prop="name">
              <el-input v-model="department_emps.userId" disabled="true" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="员工姓名" prop="name">
              <el-input v-model="department_emps.username"  disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="6">
            <el-form-item label="工号" >
              <el-input v-model="department_emps.workId" disabled="true" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="部门职位">
              <el-input v-model="department_emps.workName" disabled="true" ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelAdd">取 消</el-button>
    <el-button type="primary" @click="submitChangesDep">确 定 更 换</el-button>
  </span>
    </el-dialog>



  </div>
  </div>











</template>

<script>
  import FileSaver from 'file-saver'
  import XLSX from 'xlsx'
    export default {
        name: "department_management",
      data()
      {
        return{
          department_emp:[],
          department_emps:{
            departmentId: "",
            departmentName: "",
            userId: "",
            username: "",
            workId: "",
            workName: "",
            role:"",
            istrain:"",
            iswork:"",
          },
          selectsearch:3,
          searchInput:"",
          AddDepdialogVisable:false,
          ChangeDepdiaglogVisable:false,
          EditdialogVisable:false,
          ChangeDepVisable:true,
          dep:[],
          users:[],
          departmentvalue:"请选择部门",
          Empvalue:"请选择员工ID",
          showvalue:"排序类型(默认DepId升序)",
          options: [
            {
              value: 'DepIdasc',
              label: '(默认DepId升序)'
            },
            {
              value: 'roleAsc',
              label: '权限排序'
            }],
        }
      },
      mounted() {
        this.reloadDepartment_emp()
        this.reloadAllDepId()
        this.reloadAllnoWorkuserId()
      },
      methods:
      {
        //定义导出Excel表格事件
        exportExcel() {
          let xlsxParam = { raw: true }; //转换成excel时，使用原始的格式
          / generate workbook object from table /;
          /* 从表生成工作簿对象 */
          let table =  document.querySelector("#out-table").cloneNode(true)
          // 因为element-ui的表格的fixed属性导致多出一个table，会下载重复内容，这里删除掉
          table.removeChild(table.querySelector(".el-table__fixed-right"));
          table.removeChild(table.querySelector(".el-table__fixed"));
          let wb = XLSX.utils.table_to_book(
            table ,  //elementui 表格的id
            xlsxParam
          );

          /* 获取二进制字符串作为输出 */
          var wbout = XLSX.write(wb, {
            bookType: "xlsx",
            bookSST: true,
            type: "array"
          });
          try {
            FileSaver.saveAs(
              //Blob 对象表示一个不可变、原始数据的类文件对象。
              //Blob 表示的不一定是JavaScript原生格式的数据。
              //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
              //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
              new Blob([wbout], { type: "application/octet-stream" }),
              //设置导出文件名称
              "部门成员表.xlsx"
            );
          } catch (e) {
            if (typeof console !== "undefined") console.log(e, wbout);
          }
          return wbout;
        },
        reloadDepartment_emp()
        {

          this.$axios.post("/department/getAllDepartmentEmp",{

          }).then((res)=>{
           // alert(JSON.stringify(res.data))
              this.department_emp =[]
            this.department_emp =res.data
          })
        },
        reloadDepartment_empByRoleAsc()
        {

          this.$axios.post("/department/selectdepartment_empByrole",{

          }).then((res)=>{
            // alert(JSON.stringify(res.data))
            this.department_emp =[]
            this.department_emp =res.data
          })
        },
        reloadAllDepId()
        {
          this.dep=[],
            this.departmentvalue = "请选择部门"
          this.$axios.post("/department/selectDepIdFromDepartment").
          then((res)=>{
          //  alert(JSON.stringify(res.data))
            this.dep = res.data
          })
        },
        reloadAllnoWorkuserId()
        {
          this.users=[],
            this.Empvalue = "请选择员工Id"
          this.$axios.post("/department/selectNoWorkuserId").
          then((res)=>{
            //  alert(JSON.stringify(res.data))
            this.users = res.data
          })
        },
        selectDepByDepartmentId()
        {
          this.$axios.post("/department/selectDepByDepartmentId",{
                departmentId:this.searchInput
          }).then((res)=>{
            // alert(JSON.stringify(res.data))
            this.department_emp =[]
            this.department_emp =res.data
          })
        },
        selectDepByuserId()
        {
          this.$axios.post("/department/selectDepByuserId",{
            userId:this.searchInput
          }).then((res)=>{
            // alert(JSON.stringify(res.data))
            this.department_emp =[]
            this.department_emp =res.data
          })
        },
        openshowDeper(data)
        {
          // alert(JSON.stringify(data.departmentId))
          this.$axios.post("/department/selectDepMsgByDepartmentId",{
          departmentId:data.departmentId
        }).then((res)=>{
          alert("部门员工"+JSON.stringify(data.username).replace(/\"/g, "")+"的所属部门信息：\n部门Id："+
            JSON.stringify(res.data.departmentId).replace(/\"/g, "")+";\n部门名称："+
            JSON.stringify(res.data.departmentName).replace(/\"/g, "")+"；\n部门部长："+
            JSON.stringify(res.data.userId).replace(/\"/g, "")+"；\n部长名称："+
            JSON.stringify(res.data.username).replace(/\"/g, "")+";\n部门人数："+
            JSON.stringify(res.data.empNum).replace(/\"/g, "")
          )
        })

        },
        cancelEdit()
        {
          this.searchInput = ""
          this.EditdialogVisable = false
          this.reloadDepartment_emp()
        },
        cancelAdd()
        {
          this.searchInput = ""
          this.AddDepdialogVisable = false
          this.ChangeDepdiaglogVisable = false
          this.reloadDepartment_emp()
        },
        opendialog(data)
        {
          alert(JSON.stringify(data))
          this.employee_emps = data
        },
        openEditdialog(data)
        {
          this.department_emps.departmentId=""
          this.department_emps.departmentName=""
          this.department_emps.userId=""
          this.department_emps.username=""
          this.department_emps.workId=""
          this.department_emps.workName=""
          this.department_emps.role=""
          this.department_emps.istrain=""
          this.department_emps.iswork=""
          this.department_emps = data
         this.EditdialogVisable = true;

        },

        deleteEmp(data) {
          // alert("this.searchInput")
          // alert(JSON.stringify(data))
          this.$confirm('此操作将解散【' +JSON.stringify(data.departmentId).replace(/\"/g, "")  + '】部门的信息, 确保所有部门人员离开部门吗?是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
                  this.$axios.post("/department/removeDepartment",{
                    departmentId:data.departmentId,
                    userId:data.userId
                  }).then((res)=>{
                    return this.$message.success("解散部门成功！");
                  }).catch(()=>{
                    return this.$message.success("解散部门失败！");
                  }).finally(()=>{
                    this.reloadAllnoWorkuserId()
                    this.reloadDepartment_emp()
                    this.reloadAllDepId()
                  })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
        },

        outEmp(data) {
          // alert("this.searchInput")
          // alert(JSON.stringify(data))
          this.$confirm('此操作将移出员工【' +JSON.stringify(data.userId).replace(/\"/g, "")  + '】的部门ID为【' +JSON.stringify(data.departmentId).replace(/\"/g, "")  + '】信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

                  this.$axios.post("/department/removeDepartmentMate",{
                    userId:data.userId,
                    departmentId:data.departmentId
                  }).then((res)=>{
                      return this.$message.success(res.data.msg)
                  }).catch((error)=>{
                    return this.$message.error("移除失败，系统异常~")
                  }).finally(()=>{
                    this.reloadDepartment_emp()
                  })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消移除'
            });
          });
        },

        clearInput()
        {
          this.searchInput="";
        },
        watchsearch()
        {
          //选项
          var selectsearch = JSON.stringify(JSON.stringify(this.selectsearch)).replace(/\"/g, "")

          var userId = JSON.stringify(this.searchInput).replace(/\"/g, "")
          if(this.searchInput ==''|| this.searchInput =='undefined'||this.searchInput == null)
          {
            this.reloadDepartment_emp()
          }
          if(selectsearch =='3'&&this.searchInput !=''&&this.searchInput !='undefined'&&this.searchInput != null)
          {
            this.selectDepByDepartmentId();
          }
          if(selectsearch =='6'&&this.searchInput !=''&&this.searchInput !='undefined'&&this.searchInput != null)
          {
            this.selectDepByuserId()
          }
        },
        submitchangeDep()
        {
            this.$axios.post("/department/updateDepuserNameByuserId",{
              role:this.department_emps.role,
              userId:this.department_emps.userId,
              username:this.department_emps.username,
              workName:this.department_emps.workName,
              departmentId:this.department_emps.departmentId,
              departmentName:this.department_emps.departmentName
            }).then((res)=>{
                    this.EditdialogVisable = false
                    this.reloadDepartment_emp()
              return this.$message.success(res.data.msg)

            }).catch((error)=>{
              this.EditdialogVisable = false;
              return this.$message.error("修改失败")
            })
        },

        submitAddDep()
        {
          this.$axios.post("/department/addnewDepMate",{
            userId:this.department_emps.userId,
            username:this.department_emps.username,
            workName:this.department_emps.workName,
            workId:this.department_emps.workId,
            departmentId:this.departmentvalue,
            departmentName:this.department_emps.departmentName
          }).then((res)=>{

            return this.$message.success(res.data.msg)

          }).catch((error)=>{
            return this.$message.error("修改失败")
          }).finally(()=>{
            this.AddDepdialogVisable = false;
            this.reloadDepartment_emp()
            this.reloadAllDepId()
            this.reloadAllnoWorkuserId()
          })
        },
        submitChangesDep()
        {
          this.$axios.post("/department/changeDeper",{
            olduserId:this.department_emps.userId,
            userId:this.Empvalue,
            username:this.department_emps.username,
            workName:this.department_emps.workName,
            workId:this.department_emps.workId,
            departmentId:this.department_emps.departmentId,
            departmentName:this.department_emps.departmentName
          }).then((res)=>{
              this.$axios.post("/department/updateDepNum").then((res)=>{

              })
            return this.$message.success(res.data.msg)

          }).catch((error)=>{
            return this.$message.error("更换部长失败")
          }).finally(()=>{
            this.ChangeDepdiaglogVisable = false;
            this.reloadDepartment_emp()
            this.reloadAllDepId()
            this.reloadAllnoWorkuserId()
          })
        },
        handleClose(done) {
          this.$confirm('确认关闭？')
            .then(_ => {
              this.AddDepdialogVisable = false
              this.EditdialogVisable = false
              this.ChangeDepdiaglogVisable = false
              this.reloadAllDepId()
              this.reloadnoDepartmenter()
              done();
            })
            .catch(_ => {


            });
        },
        showDepartmentOrderBy(data)
        {
          var show = JSON.stringify(data).replace(/\"/g, "")
          if(show =='DepIdasc')
          {
            this.reloadDepartment_emp()
            return this.$message.success("已加载所有员工信息！")
          }
          if(show =='roleAsc')
          {
              this.reloadDepartment_empByRoleAsc();
            return this.$message.success("已加载所有员工信息！")
          }
        },
        showDepIdAndDepName(data)
        {
          //alert(JSON.stringify(this.dep))
          //alert(JSON.stringify(data))
          this.$axios.post("/department/selectDepNameFromDepartmentByDepId",{
            departmentId:this.departmentvalue
          }).then((res)=>{
            this.department_emps.departmentName = res.data
          })
        },
        showuserIdNoWork(data)
        {
          //alert(JSON.stringify(this.dep))
          alert(JSON.stringify(data))

        },
        addNewDeper(data)
        {
          this.department_emps.departmentId=""
          this.department_emps.departmentName=""
          this.department_emps.userId=""
          this.department_emps.username=""
          this.department_emps.workId=""
          this.department_emps.workName=""
          this.department_emps.role=""
          this.department_emps.istrain=""
          this.department_emps.iswork=""
          this.department_emps = data
          this.AddDepdialogVisable  = true;
        },
        changeNewDeper(data)
        {
          this.department_emps.departmentId=""
          this.department_emps.departmentName=""
          this.department_emps.userId=""
          this.department_emps.username=""
          this.department_emps.workId=""
          this.department_emps.workName=""
          this.department_emps.role=""
          this.department_emps.istrain=""
          this.department_emps.iswork=""
          this.department_emps = data

          this.users=[],
            this.Empvalue = "请选择员工Id"
          this.$axios.post("/department/selectNoWorkuserId",{
            departmentId :this.department_emps.departmentId,

          }).
          then((res)=>{
            //  alert(JSON.stringify(res.data))
            this.users = res.data
          })
          this.ChangeDepdiaglogVisable  = true;
        },

        returnlogin(){
          this.$store.commit("setviewPage",1);
          this.$router.push({path: '/home'})
        },
      }
    }
</script>

<style scoped>

</style>
